package com.mymarkdown.app.fx.event.hander.impl;

import com.mymarkdown.app.fx.annotation.KeyWord;
import com.mymarkdown.app.fx.assemblys.FxTreeItem;
import com.mymarkdown.app.fx.enums.FxEventEnum;
import com.mymarkdown.app.fx.event.hander.KeyWordHandler;
import com.mymarkdown.app.fx.event.model.FxEvent;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.TreeCell;
import javafx.scene.web.WebEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Objects;
import java.util.Optional;

/**
 * @author ：zenglun
 * @date ：Created in 2021/12/25 12:55 PM
 * @description：
 * @modified By：
 * @version: $
 */
@Slf4j
@KeyWord(FxEventEnum.RENAME_LOCAL_FILE)
@Component
public class ReLocalFileNameMenuHandlerImpl implements KeyWordHandler {

    private TreeCell<String> treeCell;

    private String newVal;

    private File sourceFile;

    private FxTreeItem<String> treeItem;

    @Autowired
    private WebSocketSendMessage webSocketSendMessage;


    @Override
    public void handler(WebEngine engine, FxEvent event) {
        //获取扩展名
        String parent = sourceFile.getParent();
        File renameFile = new File(parent + "/" + newVal);
        if (!renameFile.exists()){
            sourceFile.renameTo(renameFile);
        }else{
            webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("该文件已经存在!"));
        }
    }

    @Override
    public boolean afterHandler(WebEngine engine, FxEvent event) {
        treeCell = (TreeCell<String>) event.getTarget();
        treeItem = (FxTreeItem<String>) treeCell.getTreeItem();
        if (Objects.isNull(treeCell) || Objects.isNull(treeItem)){
            return false;
        }
        TextInputDialog inputDialog = new TextInputDialog(this.treeCell.getText());
        inputDialog.setHeaderText("");
        inputDialog.setTitle("重命名");
        inputDialog.setContentText("新的名称:");
        Optional<String> newVal = inputDialog.showAndWait();
        if (!newVal.isPresent()){
            return false;
        }
        this.newVal = newVal.get();
        sourceFile = treeItem.getSourceFile();
        if (Objects.isNull(sourceFile) || !sourceFile.exists()){
            return false;
        }
        return true;
    }

    @Override
    public void beforeHandler(WebEngine engine, FxEvent event) {

    }
}
